package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.RealAuth;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.service.RealAuthService;
import com.xmg.p2p.base.service.UserinfoService;
import com.xmg.p2p.base.util.JSONResult;
import com.xmg.p2p.base.util.RequireLogin;
import com.xmg.p2p.base.util.UploadUtil;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

/**
 * @BelongsProject: jinrong-website
 * @BelongsPackage: com.xmg.p2p.base.controller
 * @author: Andy
 * @date: 2021.3.22 10:22
 * @Description: 实名认证的控制器
 * @since JDK 1.8
 */
@Controller
public class RealAuthController {
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private RealAuthService realAuthService;
    @Autowired
    private ServletContext servletContext;

    /**
     * 点击实名认证显示页面
     * @param model
     * @return
     */
    @RequireLogin
    @RequestMapping("realAuth")
    public String realAuth(Model model){
        // 1、获取当前用户对象（当前用户对象中，有对应的认证方法判断和认证对象编号）
        Userinfo current = this.userinfoService.getById(UserContext.getCurrent().getId());
        /*未实名*/
        // 如果用户没有实名认证 并且realAuthId为空 跳转到realAuth填写
        if (!current.getIsRealAuth() && current.getRealAuthId() == null){
            return "realAuth";
        }else{
            /*待认证*/
            // 已经提交实名认证，但是验证还未通过
            if (!current.getIsRealAuth()){
                // 将正在认证的表示改为 true
                model.addAttribute("auditing",true);
            }else {
                /*已实名*/
                // 根据 user info 上的 realAuthId 获取实名认证对象，并放入 model 中
                model.addAttribute("realAuth",this.realAuthService.get(current.getRealAuthId()));
                // 将正在认证的表示改为 false
                model.addAttribute("auditing",false);
            }
            return "realAuth_result";
        }
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    @RequestMapping("realAuth_upload")
    @ResponseBody
    public String upload(MultipartFile file){
        /*定义了一个图片上传到哪个文件夹下*/
        String dic = "/upload";
        /*进行图片上传*/
        String fileName = UploadUtil.upload(file, this.servletContext.getRealPath(dic));
        /*图片的访问路径 /upload/fileName*/
        return dic+"/"+fileName;    // 返回相对路径，完成回显操作
    }

    /**
     * 进行提交认证
     * @param realAuth
     * @return
     */
    @RequireLogin
    @ResponseBody
    @RequestMapping("realAuth_save")
    public JSONResult realAuthSave(RealAuth realAuth){
        this.realAuthService.apply(realAuth);
        return new JSONResult();
    }

}
